package com.linkelee;

import com.alibaba.fastjson.JSON;

import com.linkelee.properties.RpcMqElementKeyBuilder;
import lombok.Builder;
import lombok.Data;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.ExchangeTypes;


/**
 * 用于mq生产端发送消息
 * @author lsl
 * @since 2019-02-22
 */

@Data
@Builder
public class MqProducerPublisher {

    private AmqpTemplate amqpTemplate;

    public void MqProducerPublisher(AmqpTemplate amqpTemplate){
        this.amqpTemplate = amqpTemplate;
    }

    /**
     * 发送消息,任意队列类型
     * @param key
     * @param message
     * @param type
     * @throws Exception
     */
    public void publishMessage(String key,String message,String type) throws Exception{
        publishMessage(key,JSON.parseObject(message),type);
    }

    /**
     * 发送消息,任意类型队列
     * @param key
     * @param message
     * @param type
     * @throws Exception
     */
    public void publishMessage(String key,Object message, String type) throws Exception {
        switch (type){
            case ExchangeTypes.FANOUT:
                publishFanoutMessage(key,message);
                break;
            case ExchangeTypes.TOPIC:
                publishTopicMessage(key,message);
                break;
            case ExchangeTypes.DIRECT:
                publishDirectMessage(key,message);
                break;
            default:
                throw new Exception("erro exchange type has be used!");
        }
    }

    /**
     * direct 队列
     * @param key
     * @param message
     */
    public void publishDirectMessage(String key,Object message) throws Exception{
        if(amqpTemplate==null){
            throw new Exception("no mq template init!");
        }
        amqpTemplate.convertAndSend(RpcMqElementKeyBuilder.DEFAULT_EXCHANGE,
                RpcMqElementKeyBuilder.buildRoutingKey(key),
                message);
    }

    /**
     * fanout 队列
     * @param key
     * @param message
     */
    public void publishFanoutMessage(String key,Object message) throws Exception{
        if(amqpTemplate==null){
            throw new Exception("no mq template init!");
        }
        amqpTemplate.convertAndSend(RpcMqElementKeyBuilder.buildExchangeName(key),
                null,
                message);
    }

    /**
     * topic队列
     * @param key
     * @param message
     */
    public void publishTopicMessage(String key,Object message) throws Exception{
        if(amqpTemplate==null){
            throw new Exception("no mq template init!");
        }
        amqpTemplate.convertAndSend(RpcMqElementKeyBuilder.buildExchangeName(key),
                RpcMqElementKeyBuilder.buildRoutingKey(key),
                message);
    }

}
